Skip to content

refactor pyclass initialization#5739

Merged
davidhewitt merged 1 commit into
PyO3:mainfrom
Icxolu:fix/3291
Jan 18, 2026
Merged

refactor pyclass initialization#5739
davidhewitt merged 1 commit into
PyO3:mainfrom
Icxolu:fix/3291

Conversation

@Icxolu
Copy link
Copy Markdown
Member

@Icxolu Icxolu commented Jan 17, 2026

This refactors the code generation for #[new] / pyclass initialization. It uses the same const probe trick we already use elsewhere in the macro machinery to dispatch the initialization based on the return type of the #[new] function. This removes the Existing case from the PyClassInitializer, making it easier to solve passing arguments to the base __new__ in a followup. Additionally it allows to return arbitrary object implementing IntoPyObject from __new__ which also takes over the Existing case.

Closes #3291
Closes #4452
Closes #5560

Copy link
Copy Markdown
Member

@davidhewitt davidhewitt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice, thank you!

Comment thread pyo3-macros-backend/src/pymethod.rs
Comment thread src/pyclass_init.rs
@davidhewitt davidhewitt mentioned this pull request Jan 18, 2026
@Icxolu
Copy link
Copy Markdown
Member Author

Icxolu commented Jan 18, 2026

Maybe a side question: The tuple initializer could be a bit confusing now that we allow arbitrary object (I also always forget which order Subclass and Baseclass should have). Should we consider deprecating that syntax and move people to use PyClassInitializer directly?

Copy link
Copy Markdown
Member

@davidhewitt davidhewitt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great, thanks!

Should we consider deprecating that syntax and move people to use PyClassInitializer directly?

I fully agree that syntax is painful, let's do it in a follow up just because it's a big enough change worth landing, reviewing & documenting in its own PR.

@davidhewitt
Copy link
Copy Markdown
Member

(we might also want to consider how to change the PyClassInitializer API to pass arguments to super __new__, or replace that API even)

@davidhewitt davidhewitt added this pull request to the merge queue Jan 18, 2026
Merged via the queue into PyO3:main with commit 0fe5ba4 Jan 18, 2026
45 checks passed
@Icxolu Icxolu deleted the fix/3291 branch January 18, 2026 16:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants